<?php

namespace App\Admin\Controllers;

use App\Models\Category;
use App\Models\File;

use App\Models\Product;
use App\Models\Resource;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\Log;

class FileController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('资源管理');
//            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('资源管理');
//            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('资源管理');
//            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(File::class, function (Grid $grid) {

            $grid->model()->orderBy('id', 'desc');
            $grid->disableExport();

            $grid->id('ID')->sortable();

            $grid->column('title', '资源名称')->display(function ($value) {
                return str_limit($value, 30, '...');
            });

            $grid->column('product_id', '关联产品名字')->display(function ($value) {
                $product = Product::select('name')->find($value);
                return $product ? $product->name : '关联产品不存在';
            });

            $grid->column('category', '资源类型')->display(function ($value) {
                $options = [
                    'pdf' => 'PDF文档',
                    'word' => 'Word文档',
                    'audio' => '音频资料',
                    'video' => '视频资料'
                ];
                $name = $options[$value];
                return $name;
            });

            $grid->column('source', '资源')->display(function ($value) {
                if ($this->local)
                {
                    return '<a href="' . asset('uploads/' . $this->local) . '" target="_blank">查看</a>';
                } else {
                    return '<a href="' . $this->external . '" target="_blank">查看</a>';
                }
            });

            $grid->column('cost', '是否付费')->display(function ($value) {
                return $value == 'free' ? '否' : '是';
            });

            $grid->column('price', '资源定价')->display(function ($value) {
                return $this->cost == 'free' ? '-' : $value;
            });

            $grid->created_at('添加时间');

            $grid->column('download_history', '下载记录')->display(function () {
                return '<a href="' . admin_base_path('downloadRecord?file_id=' . $this->id) . '">查看</a>';
            });

            $grid->filter(function ($filter){
                $filter->disableIdFilter();
                $filter->like('title', '资源名称');
                $filter->like('cost', '是否付费')
                    ->radio([
                        'charge' => '是',
                        'free' => '否'
                    ]);
                $filter->like('category', '是否为试读资源')
                    ->radio([
                        'pdf' => 'PDF文档',
                        'word' => 'Word文档',
                        'audio' => '音频资料',
                        'video' => '视频资料'
                    ]);
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        set_time_limit(600);
        return Admin::form(File::class, function (Form $form) {

            $form->text('title', '资源名称')->rules('required');

            $form->select('product_id', '产品关联')
                ->options(function ($productId) {
                    $product = Product::select('id', 'name')->where('auditing_status', 'online')->find($productId);
                    if ($product)
                        return [$product->id => $product->name];
                })
                ->ajax('/product/list')
                ->help('输入产品名字进行查找并选择')
                ->rules('required');

            $form->radio('category', '资源类型')
                ->options([
                    'pdf' => 'PDF文档',
                    'word' => 'Word文档',
                    'audio' => '音频资料',
                    'video' => '视频资料'
                ]);

            $form->file('local', '正式资源')
                ->removable()
                ->uniqueName()
                ->options([
                    'showPreview' => false
                ])
                ->help('上传文件大小不超过50Mb')
                ->rules('max:51200'); //限制上传文件大小 50mb

            $form->image('cover', '音视频试读资源封面')
                ->attribute('accept', 'image/png, image/jpeg, image/jpg')
                ->removable()
                ->uniqueName()
                ->help('图片不大于1Mb,推荐尺寸：音频 76 * 76封面, 视频封面 820 * 424. 支持格式：png、jpeg、jpg.')
                ->rules('max:1024');

            $form->file('tryout', '试读资源')
                ->options([
                    'showPreview' => false,
                ])
                ->removable()
                ->uniqueName();

            $form->textarea('external', '站外试读资源')
                ->placeholder('输入站外资源链接')
                ->help('站外资源链接');

            $form->radio('cost', '是否付费')
                ->options([
                    'free' => '免费',
                    'charge' => '收费'
                ])
                ->default('free');

            $form->number('price', '资源定价')
                ->attribute('min', '0')
                ->help('按照后台管理-定价管理中设置的兑换比例， 并非人民币金额，默认10金币, 免费则定价不起效')
                ->default(10);


            if (request()->method() == 'POST')
            {
                if ($fileInfo = request()->file('local'))
                {
                    $form->model()->size = $fileInfo->getSize();
                    $form->model()->type = $fileInfo->getMimeType();
                }
            }

            $form->display('created_at', '添加时间');
            $form->display('updated_at', '更新时间');
        });
    }
}
